package com.dzm.core.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dzm.common.exception.Assert;
import com.dzm.common.result.ResponseEnum;
import com.dzm.common.util.JwtUtils;
import com.dzm.core.entity.UserInfo;
import com.dzm.core.entity.UserLoginRecord;
import com.dzm.core.mapper.UserInfoMapper;
import com.dzm.core.service.IUserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dzm.core.service.IUserLoginRecordService;
import com.dzm.core.vo.LoginVo;
import com.dzm.core.vo.UserInfoVo;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户基本信息 服务实现类
 * </p>
 *
 * @author Dzm
 * @since 2024-09-20
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

    @Autowired
    private IUserLoginRecordService userLoginRecordService;

    @Override
    public UserInfoVo login(LoginVo loginVo, String ip) {
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();
        //验证登录信息是否合法
        Assert.notNull(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        Assert.notNull(password, ResponseEnum.PASSWORD_NULL_ERROR);
        //获取用户登录信息
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getUserType, loginVo.getUserType())
                .eq(UserInfo::getMobile, mobile);
        UserInfo userInfo = this.getOne(wrapper);
        Assert.notNull(userInfo, ResponseEnum.LOGIN_MOBILE_ERROR);
        //密码校验，且用户未被锁定
        Assert.equals(userInfo.getPassword(), SecureUtil.md5(password), ResponseEnum.LOGIN_PASSWORD_ERROR);
        Assert.equals(1, userInfo.getStatus(), ResponseEnum.LOGIN_LOKED_ERROR);

        //获取用户token信息及传给前端的用户信息
        String token = JwtUtils.createToken(userInfo.getId(), userInfo.getName());
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        userInfoVo.setToken(token);

        //添加用户登录日志
        UserLoginRecord record = new UserLoginRecord();
        record.setIp(ip);
        record.setUserId(userInfo.getId());
        userLoginRecordService.save(record);

        return userInfoVo;
    }
}
